# -*- encoding:utf-8 -*-
# @time: 2023/4/17 11:18
# @author: Maxs_hu
import base64
import datetime
import json
import time

import requests
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
    'Referer': 'http://211.86.195.226/web/seat3?area=13&segment=139558&day=2023-4-18&startTime=19:45&endTime=22:00'
}


def book_seat(token):
    url = 'http://211.86.195.226/api.php/spaces/1657/book'
    start_day = datetime.datetime(2023, 4, 17)
    today = datetime.datetime.today()
    interval = today - start_day
    segment = interval.days + 119108
    data = {
        "access_token": token,
        "userid": 200314138,
        "segment": segment,  # 这个日期, 每过一天都会+1
        "type": 1,
        "operateChannel": 2
    }
    res = requests.post(url, data=data, headers=headers)
    print(res.json())


def get_token():
    global access_token
    web = Chrome()
    web.get('http://211.86.195.226/web/seat3?area=21&segment=119108&day=2023-4-17&startTime=19:35&endTime=22:00')
    time.sleep(3)
    # 判断加载完成
    WebDriverWait(web, 30, 0.5).until(
        # 条件：直到元素加载完成
        EC.presence_of_element_located((By.XPATH, '/html/body/div[3]/div[1]/ul/li[6]/a'))
    )
    click_js = """document.evaluate('/html/body/div[3]/div[1]/ul/li[6]/a', document).iterateNext().click()"""
    web.execute_script(click_js)
    time.sleep(1)
    web.find_element(By.XPATH, '/html/body/div[11]/div/table/tbody/tr[2]/td/div/div/div[1]/input').send_keys(
        '200314138')
    web.find_element(By.XPATH, '/html/body/div[11]/div/table/tbody/tr[2]/td/div/div/div[2]/input').send_keys(
        'Th20190410')
    png = web.find_element(By.XPATH, '/html/body/div[11]/div/table/tbody/tr[2]/td/div/div/div[3]/img').screenshot_as_png
    file_name = "check.png"
    with open(file_name, "wb") as f:
        f.write(png)
    # 获取验证码
    result = base64_api(uname='ifeng', pwd='th20190410', img="check.png", typeid=1)
    print(result)
    web.find_element(By.XPATH, '/html/body/div[11]/div/table/tbody/tr[2]/td/div/div/div[3]/input').send_keys(result)
    time.sleep(1)
    web.find_element(By.XPATH, '/html/body/div[11]/div/table/tbody/tr[3]/td/div[2]/button[2]').click()
    WebDriverWait(web, 30, 0.5).until(
        # 条件：直到元素加载完成
        EC.presence_of_element_located((By.XPATH, '/html/body/div[14]/div/table/tbody/tr[2]/td/div/div'))
    )
    # 获取页面的响应头信息
    cookies = web.get_cookies()
    for item in cookies:
        if item.get('name') == "access_token":
            access_token = item.get('value')
            print(access_token)
    web.quit()
    return access_token


def base64_api(uname, pwd, img, typeid):
    with open(img, 'rb') as f:
        base64_data = base64.b64encode(f.read())  # read()字节 => b64字符串
        b64 = base64_data.decode()  # b64字符串是图片
    data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]


def main():
    start_time = time.time()
    # 获取access_token
    token = get_token()

    # 预约座位
    book_seat(token)
    end_time = time.time()
    interval = end_time - start_time
    print(interval)


if __name__ == "__main__":
    main()


